import 'dart:convert';
import 'dart:io';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/handover_new_entity.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/a_yyt/page/medical_package_area_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/utils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pc300_health_sdk/health_data_plugin.dart';

import '../../model/customer_info_model.dart';
import 'medical_check_page.dart';

class MedicalPackagePage extends BaseStatefulMvvmWidget {
  final HandoverNewInfo? info;

  MedicalPackagePage({Key? key, this.info});

  @override
  _MedicalPackagePageState createState() => _MedicalPackagePageState();
}

class _MedicalPackagePageState
    extends BaseMvvmState<MedicalPackageViewModel, MedicalPackagePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return initProvider();
  }

  @override
  Widget? buildLoadingContentView() {
    return MedicalPackageArea();
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.5,
        title: Text('健康监测'),
        actions: [
          IconButton(
              icon: Icon(Icons.qr_code_scanner),
              onPressed: () async {
                if (!HealthDeviceLinkUtils.isOnline) {
                  Toast.show("请先连接蓝牙设备");
                  return;
                }
                String result = await Utils.scan();
                var map = jsonDecode(result);
                var format = map["QrCodeFormat"];
                var obj = map["obj"];
                if (1 == format) {
                  viewModel.getOldManDetail(obj);
                }
              })
        ],
      ),
      body: loadingContentWidget,
    );
  }

  @override
  MedicalPackageViewModel createViewModel() {
    return MedicalPackageViewModel(context);
  }

  @override
  void onRetryClick() {}
}

class MedicalPackageViewModel extends BaseViewModel {
  MedicalPackageViewModel(super.context);

  var customerModel = CustomerInfoModel();

  void getOldManDetail(int oldId) {
    var map = {"customerId": oldId};
    Toast.showStateWithMsg("正在加载中...");
    HttpUtil.instance
        .getDio()
        .get(HttpApi.customerDetail, queryParameters: map)
        .then((value) async {
      Toast.cancelToast();
      if (value.statusCode != 200) {
        Toast.show(value.statusMessage ?? "");
        return;
      }
      var data = jsonDecode(value.data.toString());
      if ("0" != data["code"]) {
        showToast(data["msg"]);
        return;
      }
      var oldData = data["data"];
      MedicalElderInfo info = new MedicalElderInfo(
        name: oldData["name"],
        id: oldId,
        nurseLevelName: oldData["nurseLevelName"],
        roomNo: oldData["roomNo"].toString(),
        sexName: oldData["sexName"],
        age: oldData["age"],
      );

      AppNavigator.push(
        context,
        MedicalCheckPage(
          info: info,
          isOnConnectDevice: HealthDeviceLinkUtils.isOnline,
        ),
      );
    }).catchError((error) {
      Toast.cancelToast();
      print(error.toString());
      if (error is DioError) {
        Toast.show(getErrorMessage((error as DioError).type));
      } else {
        Toast.show(error.toString());
      }
    });
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerByCard(cardNumber);
    }
  }

  Future<void> getCustomerByCard(String cardNumber) async {
    showLoadingDialog();
    try{
      var old = await customerModel.getCardAccount(physicalCardNo: cardNumber);
      hideDialog();
      if(old.data!=null){
        getOldManDetail(old.data!.human!.id!);
      }else{
        showToast("未查询到卡信息");
      }
    }catch(e){
      showToast(e.toNetError());
      hideDialog();
    }
  }
}
